import Vue from 'vue'
import Router from 'vue-router'
import store from "../store";


const Home = () => import('../views/Home.vue')
const Login = () => import('../views/Login.vue')
const Index = () => import('../views/Index.vue')
const UserCenter = () => import('../views/UserCenter')


Vue.use(Router)

const routes = [

  {
    path: '/',
    name: "Home",
    component: Home,
    children: [
      {
        path: '/index',
        name: "Index",
        component: Index
      },
      {
        path: '/userCenter',
        name: "UserCenter",
        meta: {
          title:"个人中心"
        },
        component: UserCenter
      },
/*      {
        path: '/sys/user',
        name: "SysUser",
        component: User
      },
      {
        path: '/sys/role',
        name: "SysRole",
        component: Role
      },
      {
        path: '/sys/menu',
        name: "SysMenu",
        component: Menu
      }*/

    ]
  },
  {
    path: '/login',
    name: "Login",
    component: Login
  }
]

const route = new Router({
  routes,
  mode: 'history'
})


import {getSideMenu} from '../network/request'

route.beforeEach((to , from , next) => {


  let isLogin = window.localStorage.getItem('token')
  console.log(isLogin)
  if (isLogin) {
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }


  let hasRoute = store.state.menus.hasRoute
  console.log(hasRoute)
  if(!hasRoute) {
    getSideMenu().then(res => {

      //拿到menulist
      store.commit("setMenuList" , res.data.data.nav)
      //console.log(res.data.data.nav)

      //拿到用户权限
      store.commit("setPermList" , res.data.data.authoritys)

      //动态绑定路由
      let newRoutes = route.options.routes
      //console.log(newRoutes)
      //console.log(res.data.data.nav)
      res.data.data.nav.forEach(menu => {
        if (menu.children){
          menu.children.forEach(e => {

            //转化成路由
            let route = menuToRoute(e)

            //把路由添加到路由管理中
            if (route){
              //console.log(route)
              newRoutes[0].children.push(route)
            }
          })
        }
      })
      //console.log(newRoutes)
      route.addRoutes(newRoutes)
      hasRoute = true
      store.commit("changeRouteStatus" , hasRoute)
    })
  }

  next()
})

const menuToRoute = (menu) => {
  //console.log(menu)
  let route = {
    path: menu.path,
    component: () => import('@/views'+menu.component),
    name: menu.name,
    meta: {
      icon: menu.icon,
      title: menu.title
    }
  }

  return route
}

export default route
